package com.spdg.ring.bo;

import android.app.Activity;
import android.os.Bundle;
import cn.wolf.base.BaseBo;
import cn.wolf.base.ICallBack;

import com.spdg.ring.common.Config;
import com.spdg.ring.widget.AccessTokenKeeper;
import com.weibo.sdk.android.Oauth2AccessToken;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;
import com.weibo.sdk.android.sso.SsoHandler;

/**
 * <p>Title: 微博逻辑类      </p>
 * <p>Description: 
 * 仅绑定新浪微博
 * </p>
 * <p>@author: Eric.wsd                </p>
 * <p>Copyright: Copyright (c) 2012    </p>
 * <p>Company: HX Co., Ltd.          </p>
 * <p>Create Time: 2012-11-14             </p>
 * <p>Update Time:                     </p>
 * <p>Updater:                         </p>
 * <p>Update Comments:                 </p>
 */
public class WeiboBo extends BaseBo {
	private Weibo mWeibo;
	private static Oauth2AccessToken accessToken;

	private ICallBack icall;

	public static final String TYPE_WEIBO_BIND_SUCCESSFUL = "1001"; // 绑定成功
	public static final String TYPE_WEIBO_BIND_FAIL = "1002"; // 绑定失败
	public static final String TYPE_WEIBO_UNBIND_SUCCESSFUL = "1003"; // 解除绑定成功
	public static final String TYPE_WEIBO_UNBIND_FAIL = "1004"; // 解除绑定失败
	public static final String TYPE_WEIBO_CANCEL = "1005"; // 取消微博绑定
	public static final String TYPE_WEIBO_EXCEPTION = "1006";	//微博异常

	/**
	 * SsoHandler 仅当sdk支持sso时有效，
	 */
	public SsoHandler mSsoHandler;

	public WeiboBo(Activity activity, ICallBack icall) {
		super(activity);

		this.icall = icall;

		mWeibo = Weibo.getInstance(Config.CONSUMER_KEY, Config.REDIRECT_URL);
	}

	/**
	 * 请求绑定验证
	 */
	public void authorize() {
		// 仅当sdk支持sso时有效，
		mSsoHandler = new SsoHandler(mActivity, mWeibo);
		mSsoHandler.authorize(new AuthDialogListener());
	}

	public void unBindAuthor() {
		accessToken = AccessTokenKeeper.readAccessToken(mActivity);
		if (accessToken.isSessionValid()) {
			AccessTokenKeeper.clear(mActivity);
			icall.call(TYPE_WEIBO_UNBIND_SUCCESSFUL);
		} else {
			icall.call(TYPE_WEIBO_UNBIND_FAIL);
		}
	}

	class AuthDialogListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			accessToken = new Oauth2AccessToken(token, expires_in);
			if (accessToken.isSessionValid()) {
				// 保存token
				AccessTokenKeeper.keepAccessToken(mActivity, accessToken);
				icall.call(TYPE_WEIBO_BIND_SUCCESSFUL);
			} else {
				icall.call(TYPE_WEIBO_BIND_FAIL);
			}
		}

		@Override
		public void onCancel() {
			icall.call(TYPE_WEIBO_CANCEL);
		}

		@Override
		public void onError(WeiboDialogError arg0) {

		}

		@Override
		public void onWeiboException(WeiboException arg0) {
			icall.call(TYPE_WEIBO_EXCEPTION);
		}

	}

}
